<?php


namespace app\api\controller\v21;


use app\api\controller\v2\Auth;
use app\common\cachemodel\zl7\Zl7QuestionAiAnswerRecord;
use app\common\cachemodel\ZlRecommendDivination;
use app\common\cachemodel\ZlTarotRecords;
use app\common\lib\tarot\Tarot;
use app\common\model\Divination;
use think\Env;
use think\Log;

class UserDivination extends Auth
{
    /**
     * 塔罗占卜
     * @throws \Exception
     */
    public function tarotAdd()
    {
        $type = input('type/d', 2); // 2 自定义提问（免费）  1 推荐提问
        $question = htmlspecialchars(trim(input('question/s', '')));
        $id = input('id/d', 0);

        if ($type === 2)
        {   // 自定义问题
            if (!$question)
            {
                return show(config('code.error'), '请输入问题，再进行占卜');
            }

            if (mb_strlen($question) > 30)
            {
                return show(config('code.error'), '提问最多30字，占卜失败');
            }

            $tarotType = 1; // 自定义问题 1号牌阵 （免费）
            $gid = 0;
            $status = 1; // 1解锁 0未解锁
        } else
        {   // 获取推荐占卜信息 内的牌阵信息
            if (!$id)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $recommendTarotInfo = (new ZlRecommendDivination())->getInfoById($id, ['question', 'tarot_type', 'gid']);
            if (!$recommendTarotInfo)
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $question = $recommendTarotInfo['question'];
            $tarotType = (int)$recommendTarotInfo['tarot_type'];
            $gid = (int)$recommendTarotInfo['gid'];
            $status = 0; // 1解锁 0未解锁
        }

        // 获取塔罗占卜结果
        $tarotData = (new Tarot())->getTarot($tarotType);

        $data = [
            'uid' => $this->user['id'],
            'question' => $question,
            'type' => $type,
            'gid' => $gid,
            'status' => $status,
            'tarot_type' => $tarotType,
            'content' => json_encode($tarotData, JSON_UNESCAPED_UNICODE),
            'create_time' => $this->request->time(),
        ];
        $tarotRecordModel = new ZlTarotRecords();

        $tarotId = $tarotRecordModel->saveData($this->user['id'], $data);

        if ($tarotId)
        {
            $tarotRecordModel->divinationNumAdd($tarotType); // 占卜数量增加
            return show(config('code.success'), '占卜成功', ['tarot_id' => (int)$tarotId]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 获取塔罗占卜结果
     */
    public function getTarotDetail()
    {
        $tarotId = input('tarot_id/d', 0);

        if (!$tarotId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $tarotRecordModel = new ZlTarotRecords();
        // 获取占卜信息
        $tarotInfo = $tarotRecordModel->getInfoById($tarotId, ['id', 'uid', 'gid', 'status', 'tarot_type', 'content', 'question', 'create_time']);

        if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
        {
            return show(config('code.error'), '服务异常，占卜记录不存在');
        }
        // 获取详情返回结果信息
        $resData = $tarotRecordModel->getDetails($tarotInfo);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取塔罗占卜历史记录
     */
    public function getTarotList()
    {
        $type = input('type/d', 2);

        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        if ($type === 2)
        {
            $tarotRecordModel = new ZlTarotRecords();

            $data = $tarotRecordModel->getListPage($this->user['id']);

            $data['data'] = $tarotRecordModel->pageDataReset($data['data'], 1);

            return show(config('code.success'), '请求成功', $data);
        }

        $map['uid'] = $this->user['id'];
        $map['page'] = input('page/d', 1);
        try
        {
            $data = (new Divination())->getListPage($map);
            if ((!isset($data['data']) || empty($data['data'])) && $map['page'] === 1)
            {
                return show(200, '您的提问记录为空，立即去提问吧~', $data);
            }

            $d = [];
            if (isset($data['data']))
            {
                $oss = Env::get('host.photo');
                foreach ($data['data'] as $item)
                {
                    $aiContent = (new Zl7QuestionAiAnswerRecord())->getUserAiInfo($type, $this->user['id'], $item['id'])['content'];
                    $d[] = [
                        'id' => (int)$item['id'],
                        'question' => $item['question'],
                        'planet' => (int)$item['planet'],
                        'sign' => (int)$item['sign'],
                        'house' => (int)$item['house'],
                        'tag' => $aiContent !== null ? $oss . '/test/ai/divination_tarot_ai.png' : '',
                        'create_time' => date('Y.m.d H:i', $item['create_time']),
                    ];
                }
            }
            $data['data'] = $d;
            return show(200, '成功', $data);
        }
        catch (\Exception $e)
        {
            Log::write('获取提问历史记录失败' . $e->getMessage() . var_export(request()->param(), true), 'error', true);

            return show(config('code.error'), '网络错误');
        }
    }

    /**
     * 删除塔罗占卜记录
     */
    public function tarotDel()
    {
        $tarotId = input('tarot_id/d', 0);

        if (!$tarotId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $tarotRecordModel = new ZlTarotRecords();

        $tarotInfo = $tarotRecordModel->getInfoById($tarotId, ['uid', 'gid', 'status']);

        if (!$tarotInfo || $this->user['id'] !== (int)$tarotInfo['uid'])
        {
            return show(config('code.error'), '占卜记录不存在，删除失败');
        }

        $res = $tarotRecordModel->delData($this->user['id'], $tarotId);

        if ($res)
        {
            return show(config('code.success'), '删除成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
